package com.szl.group.config.auth.custom;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.szl.group.common.model.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.szl.group.common.enums.ResultCodeEnum.ACCESS_DENIED;

/**
 * 自定义401无权限返回.
 * AccessDeniedHandler 用来解决认证过的用户访问无权限资源时的异常
 *
 * @author shenxiaolong
 * @date 2020/06/22  4:48 PM
 */
@Slf4j
@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException {

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_OK);

        if (e != null) {
            httpServletResponse.getWriter().write(objectMapper.writeValueAsString(R
                    .builder()
                    .code(ACCESS_DENIED.getCode())
                    .message(ACCESS_DENIED.getMessage())
                    .build()));
        }
    }
}
